import store from '@/store'
import axios from 'axios'
import {Toast} from 'vant'

// create an axios instance
const service = axios.create({
    // baseURL: store.state.baseUrl, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
    config => {
        config.headers['Content-Type'] = 'application/json;charset=utf-8'
        // config.headers['TENANT-ID'] = '1'
        if (!config.headers.Authorization) {
            // config.headers["Authorization"] = "Bearer 2d68fb0a-b711-45c4-8f0d-4be529827d2b"
            config.headers["Authorization"] = "Bearer " + sessionStorage.getItem('token')
        }
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        if (response.data.code == 200) {
            return response.data.data
        } else if (response.data.code == 400) {
//处理状态码
        } else if (response.data.code == 401) {
            Toast('token失效')
        } else {
            Toast.fail({
                message: response.data.message || '错误',
                duration: 3 * 1000
            })
            return Promise.reject(new Error(response.data.message || '错误'))
        }
    },
    error => {
        switch (error.response.status) {
            case 400:
                Toast.fail({
                    message: error.response.data,
                    duration: 1500,
                })
                break
            case 401:
                // router.replace("/login");
                Toast.fail({
                    message: '跳转登陆页面',
                    duration: 1500
                })
                break
            case 405:
                Toast.fail({
                    message: 'http请求方式有误',
                    duration: 1500,
                })
                break
            case 404:
            case 500:
                Toast.fail({
                    message: '服务器出了点小差，请稍后再试',
                    duration: 1500,
                })
                break
            case 501:
                Toast.fail({
                    message: '服务器不支持当前请求所需要的某个功能',
                    duration: 1500,
                })
                break
        }
        return Promise.reject(error.response.data.msg)
    }
)

export default service
